import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import User from '../views/UserCenter.vue'
import Home from '../views/Home.vue'
import InstitudeValidate from '../views/Validate.vue'
import LevelTest from '../views/LevelTest.vue'
import store from '../store'
Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/Home',
    name: 'Home',
    component: Home
  },
  {
    path: '/User',
    name: 'user',
    meta: {
      requireAuth: true
    },
    component: User
  },
  {
    path: '/User/Validate',
    name: 'Validate',
    meta: {
      requireAuth: true
    },
    component: InstitudeValidate
  },
  {
    path: '/',
    name: 'LoginDefault',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/login',
    name: 'Login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/LevelTest',
    name: 'LevelTest',
    component: LevelTest
  }
]

// 页面刷新时，重新赋值token
if (window.sessionStorage.getItem('token')) {
  store.commit('session/login', window.sessionStorage.getItem('token'))
}

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (window.sessionStorage.getItem('token')) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})
export default router
